// 1. 安装依赖：npm install express mongoose

// app.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();

// 中间件配置
app.use(express.json()); // 解析JSON请求体 

// 连接MongoDB
mongoose.connect('mongodb://localhost:27017/mydb', { 
  useNewUrlParser: true, 
  useUnifiedTopology: true 
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.error(err));

// 定义数据模型
const BookSchema = new mongoose.Schema({
  title: { type: String, required: true },
  author: String,
  price: Number
});
const Book = mongoose.model('Book', BookSchema); // 

// CRUD路由
app.post('/books', async (req, res, next) => {
  try {
    const newBook = await Book.create(req.body);
    res.status(201).json(newBook);
  } catch (err) {
    next(err); // 错误传递到中间件 
  }
});

app.get('/books', async (req, res) => {
  const books = await Book.find();
  res.json(books);
});

// 错误处理中间件（必须放在路由之后）
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: err.message });
});

app.listen(3000, () => console.log('Server running on port 3000'));